﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using Telerik.WinControls;
using Telerik.WinControls.UI;

using Aspose.Cells;
using Aspose.Cells.Rendering;
using System.Configuration;

namespace UnigenReport
{
    public static class PackingTypeEnum
    {
        public static string Type1 { get { return "Carton"; } }
        public static string Type2 { get { return "Pallet"; } }
        public static string Type3 { get { return "Mix"; } }
    }

    public static class Common
    {
        #region Connection string exe
        private static string configFileExe = "UnigenReport.exe";
        public static void LockConfigFile()
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(configFileExe);
                ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
                if (!section.SectionInformation.IsProtected)
                {
                    // Encrypt the section.
                    section.SectionInformation.ProtectSection(
                        "DataProtectionConfigurationProvider");
                }
                config.Save();
            }
            catch (Exception ex)
            {
                return;
            }
        }
        public static void UnLockConfigFile()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(configFileExe);
            ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
            if (section.SectionInformation.IsProtected)
            {
                // Remove encryption.
                section.SectionInformation.UnprotectSection();
            }
            config.Save();
        }
        public static bool ChangeConnectionString(string cnn)
        {
            try
            {
                UnLockConfigFile();
                Configuration config = ConfigurationManager.OpenExeConfiguration("UnigenReport.exe");
                ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
                section.ConnectionStrings["UnigenReport.Properties.Settings.UnigenConnectionString"].ConnectionString = cnn;
                config.Save();
                LockConfigFile();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        #endregion

        #region Message
        //--Show done
        public static void ShowDoneMess(string text)
        {
            RadMessageBox.Show(text, "Infomation", MessageBoxButtons.OK, RadMessageIcon.Info);
        }
        //--Show notice
        public static void ShowNoticeMess(string text)
        {
            RadMessageBox.Show(text, "Notify", MessageBoxButtons.OK, RadMessageIcon.Exclamation);
        }
        //--Show error
        public static void ShowErrorMess(string text)
        {
            RadMessageBox.Show(text, "Error", MessageBoxButtons.OK, RadMessageIcon.Error);
        }
        //--Show question
        public static DialogResult ShowQuestion(string text)
        {
            return RadMessageBox.Show(text, "Confirm", MessageBoxButtons.OKCancel, RadMessageIcon.Question);
        }

        //--Data selection require
        public static void ShowSelectionRequire()
        {
            RadMessageBox.Show("No row selected!", "Notify", MessageBoxButtons.OK, RadMessageIcon.Exclamation);
        }
        //--Save data
        public static void ShowSaveSuccess()
        {
            RadMessageBox.Show("Successfully saved!", "Infomation", MessageBoxButtons.OK, RadMessageIcon.Info);
        }
        //--Unsuccess data
        public static void ShowSaveUnSuccess()
        {
            RadMessageBox.Show("Save failed!", "Error", MessageBoxButtons.OK, RadMessageIcon.Error);
        }
        #endregion

        #region GUI
        /// <summary>
        /// Tạo số thứ tự cho grid
        /// </summary>
        /// <param name="gvw">Grid nguồn</param>
        public static void SetNo(RadGridView grv)
        {
            for (int i = 0; i < grv.RowCount; i++)
            {
                grv.Rows[i].Cells["No"].Value = i + 1;
            }
        }

        /// <summary>
        /// Tạo một form để chứa UserControl
        /// </summary>
        /// <param name="uc">User control cần add</param>
        /// <param name="formTitle">Tiêu đề form</param>
        /// <param name="x">Chiều dài</param>
        /// <param name="y">Chiều cao</param>
        /// <returns></returns>
        public static RadForm CreateForm(UserControl uc, string formTitle, int x, int y)
        {
            var form = new RadForm();
            form.Text = formTitle;
            form.Size = new System.Drawing.Size(x, y);
            form.MinimumSize = new System.Drawing.Size(x, y);
            form.StartPosition = FormStartPosition.CenterScreen;
            form.ShowInTaskbar = false;
            form.KeyPreview = true;
            form.Controls.Add(uc);

            return form;
        }

        public static void SetMenuShortcut(
            CommandBarButton btnInsert,
            CommandBarButton btnUpdate,
            CommandBarButton btnDelete,
            CommandBarButton btnGetData,
            CommandBarButton btnCloseForm)
        {
            //(btnInsert ?? new CommandBarButton()).Shortcuts.Add(new RadShortcut(Keys.None, Keys.F1));
            //(btnUpdate ?? new CommandBarButton()).Shortcuts.Add(new RadShortcut(Keys.None, Keys.F2));
            //(btnDelete ?? new CommandBarButton()).Shortcuts.Add(new RadShortcut(Keys.None, Keys.F3));
            //(btnGetData ?? new CommandBarButton()).Shortcuts.Add(new RadShortcut(Keys.None, Keys.F4));
            //(btnCloseForm ?? new CommandBarButton()).Shortcuts.Add(new RadShortcut(Keys.None, Keys.Escape));
        }

        /// <summary>
        /// Chuyển đổi giá trị text sang decimal từ MaskedTextBox
        /// </summary>
        /// <param name="textBox"></param>
        /// <returns></returns>
        public static decimal MaskValueDecimal(RadMaskedEditBox textBox)
        {
            return decimal.Parse(textBox.Text.Replace(",", ""));
        }

        /// <summary>
        /// Chuyển đổi giá trị text sang decimal từ MaskedTextBox
        /// </summary>
        /// <param name="textBox"></param>
        /// <returns></returns>
        public static int MaskValueInt(RadMaskedEditBox textBox)
        {
            return int.Parse(textBox.Text.Replace(",", ""));
        }

        /// <summary>
        /// Hàm tự động in ngầm file excel ko cần mở Printer Dialog
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="copiesNummber"></param>
        /// <param name="startRow"></param>
        /// <param name="rowHeightTitle"></param>
        public static void PrintExcelAuto(string fileName, int copiesNummber, int startRow = 4, int rowHeightTitle = 30)
        {
            var config = new SystemConfig.UserConfig();

            var options = new ImageOrPrintOptions();
            options.PrintingPage = PrintingPageType.IgnoreStyle;

            if (String.IsNullOrEmpty(config.PrinterName))
            {
                PrintDialog print = new PrintDialog();

                if (print.ShowDialog() == DialogResult.OK)
                {
                    config.PrinterName = print.PrinterSettings.PrinterName;
                    SystemConfig.Save();
                }
                else
                    return;
            }

            var workbook = new Workbook(fileName);
            int sheet = workbook.Worksheets.Count;
            for (int j = 0; j < sheet; j++)
            {
                var worksheet = workbook.Worksheets[j];
                worksheet.IsGridlinesVisible = false;
                workbook.Save(fileName);

                var workbook1 = new Workbook(fileName);
                Worksheet worksheet1;
                //Get the second sheet.
                worksheet1 = workbook1.Worksheets[j];
                worksheet1.Cells.SetRowHeightPixel(startRow, rowHeightTitle);
                worksheet.IsGridlinesVisible = true;
                workbook1.Save(fileName);
                var workbook2 = new Workbook(fileName);
                //Get the second sheet.
                Worksheet worksheet2 = workbook2.Worksheets[j];

                var strPrintName = config.PrinterName;

                for (int i = 0; i < copiesNummber; i++)
                {
                    SheetRender sr = new SheetRender(worksheet2, options);
                    if (sr.PageCount > 0)
                    {
                        //Kết nối máy in
                        try
                        {
                            sr.ToPrinter(strPrintName);
                        }
                        catch (Exception e)
                        {
                            //Nếu ko kết nối được thì yêu cầu chọn lại
                            if (e.Message.Contains("Printer not found"))
                            {
                                PrintDialog print = new PrintDialog();

                                Common.ShowNoticeMess("Không thể kết nối máy in. Vui lòng chọn lại!");

                                if (print.ShowDialog() == DialogResult.OK)
                                {
                                    strPrintName = config.PrinterName = print.PrinterSettings.PrinterName;
                                    SystemConfig.Save();
                                    sr.ToPrinter(strPrintName);
                                }
                                else
                                    return;
                            }
                        }
                        //end Kết nối máy in
                    }
                }
            }

        }

        /// <summary>
        /// Đặt tự giãn dòng cho merged cell
        /// </summary>
        /// <param name="worksheet"></param>
        public static void SetAutoFitMergedCells(Worksheet worksheet)
        {
            //Create an object for AutoFitterOptions
            var options = new AutoFitterOptions
            {
                AutoFitMergedCells = true
            };
            //Set auto-fit for merged cells
            //Autofit rows in the sheet(including the merged cells)
            worksheet.AutoFitRows(options);
        }
        #endregion
    }

    public partial class InvoiceDetail
    {
        public InvoiceDetail Clone()
        {
            var invoiceDetail = new InvoiceDetail();
            invoiceDetail.InvoiceDetailId = this.InvoiceDetailId;
            invoiceDetail.InvoiceId = this.InvoiceId;
            invoiceDetail.WO = this.WO;
            invoiceDetail.PO = this.PO;
            invoiceDetail.ProductCode = this.ProductCode;
            invoiceDetail.ProductName = this.ProductName;
            invoiceDetail.Unit = this.Unit;
            invoiceDetail.Quantity = this.Quantity;
            invoiceDetail.Price = this.Price;
            invoiceDetail.ExportPrice = this.ExportPrice;
            invoiceDetail.MaterialPrice = this.MaterialPrice;
            invoiceDetail.Amount = this.Amount;
            invoiceDetail.ExportAmount = this.ExportAmount;
            invoiceDetail.UhanCodeUsing = this.UhanCodeUsing;

            return invoiceDetail;
        }
    }

    public partial class InvoicePackingList
    {
        public InvoicePackingList Clone()
        {
            var invoiceDetail = new InvoicePackingList();

            invoiceDetail.InvoiceId = this.InvoiceId;
            invoiceDetail.InvoiceId = this.InvoiceId;
            invoiceDetail.WO = this.WO;
            invoiceDetail.ProductCode = this.ProductCode;
            invoiceDetail.ProductName = this.ProductName;
            invoiceDetail.Unit = this.Unit;
            invoiceDetail.Quantity = this.Quantity;
            invoiceDetail.InnerQuantity = this.InnerQuantity;
            invoiceDetail.CartonQuantity = this.CartonQuantity;
	        invoiceDetail.PalletQuantity = this.PalletQuantity;
	        invoiceDetail.PackageUnit = this.PackageUnit;
	        invoiceDetail.PackageNo = this.PackageNo;
	        invoiceDetail.Weight = this.Weight;
	        invoiceDetail.Dimension = this.Dimension;

            return invoiceDetail;
        }
    }
    
    public partial class WorldOrder
    {
        public WorldOrder Clone()
        {
            var wo = new WorldOrder();
            wo.WOId = this.WOId;
	        wo.WO = this.WO;
            wo.PO = this.PO;
            wo.SO = this.SO;
	        wo.ProductId = this.ProductId;
	        wo.Ordered = this.Ordered;
	        wo.Shipped = this.Shipped;
            wo.Debit = this.Debit;
	        wo.Remained = this.Remained;
	        wo.Active = this.Active;
            wo.Closed = this.Closed;

            return wo;
        }
    }

    public partial class ShipAddress
    {
        public ShipAddress Clone()
        {
            var sa = new ShipAddress();
            	sa.ShipAddressId = this.ShipAddressId;
	            sa.Type = this.Type;
	            sa.Name = this.Name;
	            sa.Address = this.Address;
	            sa.Phone = this.Phone;
	            sa.Fax = this.Fax;
	            sa.Active = this.Active;
            return sa;
        }
    }

    public partial class Product
    {
        public Product Clone()
        {
            var p = new Product();
            p.ProductId = this.ProductId;
            p.UnitId = this.UnitId;
            p.Cost = this.Cost;
            p.SalePrice = this.SalePrice;
            p.Active = this.Active;
            p.ProductCode = this.ProductCode;
            p.ProductName = this.ProductName;
            p.ProductNameVi = this.ProductNameVi;
            p.HSCode = this.HSCode;
            p.UhanCodeUsing = this.UhanCodeUsing;
            return p;
        }
    }

    public partial class PackingStandard
    {
        public PackingStandard Clone()
        {
            var p = new PackingStandard();
            p.PackingId = this.PackingId;
	        p.ProductId = this.ProductId;
	        p.QtyPerInnerBox = this.QtyPerInnerBox;
	        p.WeightOfInnerBox = this.WeightOfInnerBox;
	        p.QtyPerShippingBox = this.QtyPerShippingBox;
	        p.WeightOfShippingBox = this.WeightOfShippingBox;
	        p.CartonTypeId = this.CartonTypeId;
            p.Active = this.Active;
            return p;
        }
    }

    public partial class ShippingRequest
    {
        public ShippingRequest Clone()
        {
            var sr = new ShippingRequest();
            sr.RequestId = this.RequestId;
            sr.Status = this.Status;
            sr.WOId = this.WOId;
            sr.Quantity = this.Quantity;
            sr.ShipAddressId = this.ShipAddressId;
            sr.FinishedDate = this.FinishedDate;
            sr.RequiredDate = this.RequiredDate;
            sr.CreatedDate = this.CreatedDate;
            sr.Active = this.Active;
            return sr;
        }
    }
}
